<template>
  <el-upload
    id="audioUpload"
    class="avatar-uploader"
    action="#"
    :show-file-list="true"
    :multiple="false"
    :file-list="fileList"
    :limit="props.numLimit"
    :http-request="uploadSectionFile"
    :before-upload="beforeAvatarUpload"
    :before-remove="beforeAvatarRemove"
    :on-preview="handleChangeAudio">
    <el-button slot="trigger"  type="primary" :loading="loading">选取文件</el-button>
    <div slot="tip" class="el-upload__tip">
      <p style="margin: 0;margin-left: 10px;">只能上传mp3/m4a文件，且不超过5M</p>
  </div>

  <el-dialog v-model="audioDialog" width="30%" append-to-body title="音频" :before-close="handleClose">
    <audio  v-if="audioSrc.indexOf('m4a') == -1" :src="audioSrc"  class="audiobox" ref="audioDom" controls></audio>
    <span v-else>暂不支持.m4a格式在线播放</span>
  </el-dialog>
</el-upload>
</template>

<script setup lang='ts'>
import { ref, watch, reactive } from 'vue';
import OSS from 'ali-oss';
import useCurrentInstance from '@/utils/useCurrentInstance';

const { proxy } = useCurrentInstance()
let emit = defineEmits(['upload-success'])
let audioDialog = ref(false)
let loading = ref(false)
let fileName = ref('')
let audioDuration = 0 as number | string
let fileList = ref([]) as any
let audioSrc = ref('')
let audioDom = ref()
const props = defineProps({
  audios: {
    type: Array,
    default: function() {
      return []
    }
  },
  numLimit: {
    // 最大允许上传个数
    type: Number,
    default: 1
  },
  audioBaseUrl: {
    // 已上传图片服务器路径
    type: String,
    default:'/api/enterprise/common/upload'
  }
})
let config = reactive({
  aliyunServerURL:'',
  accessid:'',
  AccessKeySecret:'',
  expiration:'',
  SecurityToken:'',
  policyBase64:'',
  signature:''
})
watch(
  ()=>[props.audios],
  ()=>{
    const isArray = Array.isArray(props.audios)
    if (isArray && props.audios.length > 0) {
      fileList.value = JSON.parse(JSON.stringify(props.audios))
      audioSrc.value = fileList.value[0].url
    } else {
      fileList.value = []
    }
  },
  {
    deep:true,
    immediate:true
  }
)
const handleChangeAudio = (file) => {
  audioSrc.value = file.url
  audioDialog.value = true
}

const beforeAvatarUpload = (file) => {
  // 文件类型进行判断
  const isAudio = file.type === "audio/mp3" || file.type === "audio/mpeg" || file.type === "audio/x-m4a";
  // 限制上传文件大小
  const isLt2M = file.size / 1024 / 1024 < 5;
  // const isTime60S = audioDuration >= 60 ? true : '';
  // 获取时长
  getTimes(file);
  if (!isAudio) {
    proxy.$message.error("上传文件只能是Mp3格式!");
      fileList.value = [];
  } else {
      if (!isLt2M) {
        proxy.$message.error("上传文件大小不能超过 5MB!");
        fileList.value = [];
      } else {
          // if (!isTime60S) {
          //   proxy.$message.error("上传文件时长不能超过60秒!");
          //   fileList.value = [];
          // }
      }
  }
  return isAudio && isLt2M
}
const beforeAvatarRemove = (file,fileList) => {
  emit('upload-success','')
  return true
}
//上传进度
const progress = (p, checkpoint) => {
  if(Math.floor(p* 100) == 100){
    loading.value = false
  }
}
const uploadSectionFile = (option) => {
  loading.value = true
  let file = option.file
  proxy.$api.uploadFile({file_type:'file'}).then(res => {
    // 定义上传文件的名字+后缀
    const aliyunilFeKey = res.result.token.Path + new Date().getTime() + Math.floor(Math.random() * 150) +'.'+file.name.split('.')[1]
    fileName.value = file.name
    config.aliyunServerURL=`https://${res.result.token.Bucket}.${res.result.token.Region}.aliyuncs.com/`
    let client = new OSS({
        accessKeyId: res.result.token.AccessKeyId,
        accessKeySecret: res.result.token.AccessKeySecret,
        stsToken: res.result.token.SecurityToken,
        region: res.result.token.Region,
        bucket: res.result.token.Bucket,
        secure:true
    })

    // 调用oss上传接口
    client.multipartUpload(aliyunilFeKey, file, {progress}).then(response=>{
      if (response.res.status === 200) {
          proxy.$message({
            type:'success',
            message:'上传成功'
          })
          audioSrc.value = config.aliyunServerURL+aliyunilFeKey
          fileList.value = [{name:new Date().getTime() + Math.floor(Math.random() * 150) +'.'+file.name.split('.')[1],url:audioSrc.value}];
          emit('upload-success',config.aliyunServerURL+aliyunilFeKey)
      }else{
        fileList.value = [];
        proxy.$message({
          type:'error',
          message:'上传失败'
        })
        loading.value = false
      }
    }).catch(function (err) { console.error('error: ', err) })
  })
}

const getTimes = (file) => {
  var content = file;
  var url = URL.createObjectURL(content);
  var audioElement = new Audio(url) as any;
  audioElement.addEventListener("loadedmetadata", (_event) => {
      audioDuration = parseInt(audioElement.duration);
  });
 }

const handleClose = () => {
  audioSrc.value = ''
  audioDialog.value = false
}
</script>

<style lang='scss' scoped>
audio {
  width: 100%;
  outline: none;
}
</style>
